#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <unistd.h>
#include <sys/shm.h>
#include <sys/ipc.h>

#define ARRAY_SIZE 40000
#define MALLOC_SIZE 100000
#define SHM_SIZE 100000
#define SHM_MODE 0600

char array[ARRAY_SIZE];

int main() {
	int shmid;
	char *ptr, *shmptr;
	key_t key;
	
	printf("array[] from %lx to %lx\n", (unsigned long)&array[0], \
								(unsigned long)&array[ARRAY_SIZE]);
	printf("stack around %lx\n", (unsigned long)&shmid);

	if ((ptr=malloc(MALLOC_SIZE)) == NULL) {
		printf("malloc error: %s\n", strerror(errno));
		return -1;
	}
	printf("malloced from %lx to %lx\n", (unsigned long)ptr, \
									(unsigned long)ptr+MALLOC_SIZE);
	
	key = ftok(".", 1);
	if ((shmid=shmget(key, SHM_SIZE, SHM_MODE|IPC_CREAT)) < 0) {
		printf("shmget error: %s\n", strerror(errno));
		return -1;
	}

	printf("%d %d\n", key, shmid);

	if ((shmptr=shmat(shmid, 0, 0)) == (void*)-1)  {
		printf("shmat error: %s\n", strerror(errno));
		return -1;
	}
	printf("shared from %lx to %lx\n", (unsigned long)shmptr, \
									(unsigned long)shmptr+SHM_SIZE);

	shmdt(shmptr);
	if (shmctl(shmid, IPC_RMID, 0) < 0) {
		printf("shmctl error: %s\n", strerror(errno));
		return -1;
	}

	return 0;
}
